package com.htjx.mall.services;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.htjx.mall.commons.mappers.SequenceMapper;
import com.htjx.mall.commons.models.Sequence;
import com.htjx.mall.commons.models.enums.SeqType;
import com.htjx.mall.commons.utils.Dates;

/**
 * 序列号生成器；生成规则：8位日期+8位数字，如：2014070700000001
 * 
 * @author jingrenlang
 * 
 */
@Service
public class SequenceManager {

	@Autowired
	private SequenceMapper sequenceMapper;
	@Autowired
	private TransactionTemplate transactionTemplate;

	public long[] buildBatchSeq(final SeqType seqType, final int count) {
		final Date now = new Date();
		int[] seqArray = transactionTemplate.execute(new TransactionCallback<int[]>() {
			@Override
			public int[] doInTransaction(TransactionStatus status) {
				Sequence currSeq = sequenceMapper.selectOneWithLock(seqType);
				
				int start = currSeq.getCurrent_value() + 1;
				if (!Dates.toYYYYMMDD(currSeq.getLast_date()).equals(Dates.toYYYYMMDD(now))) {
					start = 1;
				}
				int[] result = new int[count];
				for (int i = 0; i < count; i++) {
					result[i] = i + start;
				}
				currSeq.setCurrent_value(result[count - 1]);
				currSeq.setLast_date(now);
				sequenceMapper.updateOne(currSeq);
				return result;
			}
		});
		
		return Sequence.generateSequence(seqType, count, seqArray, now);

//		long[] retVal = new long[count];
//		// 格式化
//		for (int i = 0; i < count; i++) {
//			retVal[i] = Long.valueOf(String.format("%s%08d", Dates.toYYYYMMDD(now), seqArray[i]));
//		}
//		return retVal;
	}
}
